package com.yiyi.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * User: YIYI
 * Date: 2021-08-10
 * Time: 15:59
 * Description: response 返回封装类
 */

@Slf4j
public class ResponseUtil {

    /**
     * 使用response输出JSON
     *
     * @param response
     * @param resultMap
     */
    public static void out(HttpServletResponse response, Map<String, Object> resultMap) {

        ServletOutputStream out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getOutputStream();
            String str = JSONObject.toJSONString(resultMap);
            out.write(str.getBytes("UTF-8"));
        } catch (Exception e) {
            log.error(e + "输出JSON出错");
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Map<String, Object> resultMap(boolean success, int stateCode, String msg) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("success",success);
        data.put("code",stateCode);
        data.put("msg",msg);
        return  data;
    }
}